//
//  HomeStatusService.m
//  SinaWebo
//
//  Created by Pink Elephant on 15/4/15.
//  Copyright (c) 2015年 亦心. All rights reserved.
//

#import "HomeStatusService.h"
#import "HttpUtil.h"
#import "MJExtension.h"
#import <SDWebImageManager.h>
#import "HomeStatusCacheTool.h"
#import "Status.h"
#import "Photo.h"
#import "TextType.h"
#import "EmotionTool.h"
#import "UserPerfenceUtil.h"
#import "NSRegularExpression+Extension.h"

@implementation HomeStatusService
+(void)getHomeStatusDataWith:(HomeRequest *)request success:(void (^)(HomeResponse *))success failure:(void (^)(NSError *))failure{
    // 1.先从缓存里面加载
    NSArray *statusArray = [HomeStatusCacheTool statuesWithParam:request];
    if (statusArray.count) { // 有缓存
        // 传递了block
        if (success) {
            HomeResponse *result = [[HomeResponse alloc] init];
            result.statuses = statusArray;
            success(result);
        }
    }else{
        NSString *url = @"https://api.weibo.com/2/statuses/home_timeline.json";
        [HttpUtil getWithURL:url params:request.mj_keyValues success:^(NSDictionary *responseObject) {
            if (success) {
                HomeResponse *result=[HomeResponse mj_objectWithKeyValues:responseObject];
                [self caseImageWithData:result success:success];
            }
        } failure:^(NSError *error) {
            if (failure) {
                failure(error);
            }
        }];
    }
}

#pragma mark 缓存图片
+ (void)caseImageWithData:(HomeResponse *)result success:(void (^)(HomeResponse *))success{
    dispatch_group_t group = dispatch_group_create();
    for (Status *status in result.statuses) {
        //缓存一张图片
        if (status.pic_urls.count == 1 || status.retweeted_status.pic_urls.count == 1){
            Photo *photo;
            if (status.pic_urls.count == 1) {
                photo = status.pic_urls.firstObject;
            }else{
                photo = status.retweeted_status.pic_urls.firstObject;
            }
            dispatch_group_enter(group);
            [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:photo.thumbnail_pic] options:SDWebImageRetryFailed progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                if (finished) {
                    dispatch_group_leave(group);
                }
            }];
        }
        
    }
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        success(result);
        [HomeStatusCacheTool addStatuses:result.statuses];
    });
    
}

@end
